<script setup lang="ts">
  import { computed, nextTick, PropType, ref } from 'vue'
  import DetectionResultFillModal from './DetectionResultFillModal.vue'
  import { useGetDetectGoodList } from '@/services/pages/return-factory/useReturnFactory'
  import { ElTable, ElTableColumn, TableInstance } from 'element-plus'
  import { HMessageBox } from '@/components/common/message'

  const { goodList, getGoodListLoading, getGoodList } = useGetDetectGoodList()

  defineOptions({
    name: 'DetectionDetailsDetectionList',
  })

  const props = defineProps({
    detail: {
      type: Object as PropType<ReturnFactoryDetectDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 检测报告填写弹窗显示状态
  const detectResultFillModalVisible = ref(false)

  // 设备清单选择列表
  const goodSelectedList = ref<Array<ReturnFactoryDetectGood>>([])

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 表格图片列的列宽
  const tablePictureColumnWidth = computed(() => {
    const max = Math.max(...goodList.value.map((good) => good.repairGoodsImages.length))
    return (max || 1) * 75
  })

  /**
   * 选择清单
   * @param {Array<ReturnFactoryDetectGood>} goodList - 设备清单
   */
  const handleGoodSelect = (goodList: Array<ReturnFactoryDetectGood>) => {
    goodSelectedList.value = goodList
  }

  /**
   * 检测结果点击事件
   */
  const onDetectResultFillClick = () => {
    nextTick(() => {
      if (goodSelectedList.value.length === 0) {
        if (tableInstance.value) {
          goodList.value.forEach((good) => {
            if (good.status === 0) {
              tableInstance.value.toggleRowSelection(good, true)
            }
          })
        }
      }

      if (goodSelectedList.value.some((item) => item.status !== 0)) {
        HMessageBox.error('只能选择待检测的设备')
        return
      }

      detectResultFillModalVisible.value = true
    })
  }

  /**
   * 检测结果填写弹窗更新事件
   */
  const onUpdate = () => {
    emits('update')
    getGoodList(props.detail.id)
  }

  defineExpose({
    getGoodList,
  })
</script>

<template>
  <div v-loading="getGoodListLoading" class="detection-list-return-factory-detection-detail">
    <div class="title-wrapper">
      <div class="text">检测清单</div>
      <h-plain-button
        v-if="[0, 1].includes(props.detail.status)"
        :height="20"
        :padding-lr="2"
        @click="onDetectResultFillClick"
        >填写检测结果</h-plain-button
      >
    </div>
    <el-table
      ref="tableInstance"
      :border="true"
      stripe
      :data="goodList"
      :tooltip-options="{
        popperClass: 'return-factory-reason',
      }"
      @selection-change="handleGoodSelect"
    >
      <!-- 选择 -->
      <el-table-column
        type="selection"
        width="50"
        :align="'center'"
        fixed="left"
        :selectable="(row: ReturnFactoryDetectGood) => row.status === 0"
      />

      <!-- 序号 -->
      <el-table-column label="序号" type="index" width="50" :align="'center'" fixed="left" />

      <!-- 序列号（序列号） -->
      <el-table-column label="序列号（序列号）" width="140" prop="snCode" show-overflow-tooltip />

      <!-- 设备类型 -->
      <el-table-column label="设备类型" width="100" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.type === 1 ? '成品' : '物料' }}
        </template>
      </el-table-column>

      <!-- 设备型号 -->
      <el-table-column label="设备型号" prop="goodsModel" width="100" show-overflow-tooltip />

      <!-- 设备编号 -->
      <el-table-column label="设备编号" width="200" prop="goodsCode" show-overflow-tooltip />

      <!-- 设备名称 -->
      <el-table-column label="设备名称" width="240" prop="goodsName" show-overflow-tooltip />

      <!-- 规格 -->
      <el-table-column label="规格" width="240" prop="goodsSpecName" show-overflow-tooltip />

      <!-- 数量 -->
      <el-table-column label="数量" width="100" prop="qty" />

      <!-- 返厂描述 -->
      <el-table-column label="返厂描述" width="160" prop="descr" show-overflow-tooltip />

      <!-- 检测结果 -->
      <el-table-column label="检测结果" width="240" prop="checkResult" show-overflow-tooltip />

      <!-- 解决措施 -->
      <el-table-column label="解决措施" width="140" prop="measure" show-overflow-tooltip />

      <!-- 质保开始 -->
      <el-table-column label="质保开始" width="140" prop="warrantyStartTime" />

      <!-- 质保结束 -->
      <el-table-column label="质保结束" width="140" prop="warrantyEndTime" />

      <!-- 返厂图片 -->
      <el-table-column label="返厂图片" :width="tablePictureColumnWidth">
        <template #default="{ row }">
          <div class="image-list">
            <h-image
              v-for="(img, index) in row.repairGoodsImages"
              :key="index"
              :show-del-btn="false"
              :src="img"
              :preview-src-list="row.images"
              :padding="2"
              :width="60"
              :height="37.5"
              :initial-index="index"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 状态 -->
      <el-table-column label="状态" width="80" fixed="right" :align="'center'">
        <template #default="{ row }">
          <div class="flex_justify_center">
            <h-status v-if="row.status === 0" type="warning">待检测</h-status>
            <h-status v-else type="success">已检测</h-status>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 检测结果填写弹窗 -->
    <detection-result-fill-modal
      v-model:visible="detectResultFillModalVisible"
      :good-list="goodSelectedList"
      :detect-id="props.detail.id"
      @update="onUpdate"
    />
  </div>
</template>

<style scoped lang="scss">
  :deep(.return-factory-reason) {
    max-width: 300px !important;
    max-height: 150px !important;
    overflow: auto !important;
  }

  .detection-list-return-factory-detection-detail {
    display: flex;
    flex-direction: column;
    row-gap: 6px;

    .title-wrapper {
      display: flex;
      column-gap: 5px;

      .text {
        font-size: 12px;
        font-weight: bold;
        padding-left: 6px;
        border-left: 3px solid $primaryColor;
        line-height: 20px;
      }
    }

    .image-list {
      display: flex;
      column-gap: 5px;
    }
  }
</style>
